package com.zkingsoft.wechat;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.matrix.core.exception.GlobleException;
import com.matrix.core.pojo.AjaxResult;
import com.matrix.core.tools.LogUtil;
import com.matrix.core.tools.StringUtils;
import com.matrix.core.tools.UUIDUtil;
import com.matrix.core.web.BaseAction;
import com.zkingsoft.common.constance.AppConstance;
import com.zkingsoft.common.constance.AppMessageCode;
import com.zkingsoft.laqeelin.bean.BizUser;
import com.zkingsoft.laqeelin.dao.BizUserDao;
import com.zkingsoft.laqeelin.service.BizUserService;
import com.zkingsoft.redis.RedisUserLoginUtils;
import com.zkingsoft.tools.AES;
import com.zkingsoft.tools.HttpCurlUtil;
import com.zkingsoft.tools.WxUtils;

import net.sf.json.JSONObject;

/**
 * @description (用户表)
 * @author 何明
 * @date 2018-05-23 00:08
 */
@Controller
@RequestMapping(value = "wxapi/user")
public class WxUserAction extends BaseAction {

	@Autowired
	private BizUserService bizUserService;

	@Autowired
	RedisUserLoginUtils redisUserLoginUtils;
	@Autowired
	private BizUserDao bizUserDao;

	@Value("${debug}")
	private String isDebug;

	/**
	 * 小程序登录
	 * 
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date 2018年5月23日
	 * @param code
	 * @return
	 * @throws IOException
	 * @throws HttpException
	 */
	@RequestMapping(value = "/login/{keys}")
	public @ResponseBody AjaxResult wxLogin(@PathVariable("keys") String code) throws HttpException, IOException {
		AjaxResult res = new AjaxResult();
		if (StringUtils.isNotBlank(code)) {
			String requrl = WeChatApiTools.getXcxLoginUrl(code);
			String reslutData = HttpCurlUtil.sendGetHttp(requrl, null);
			JSONObject json = JSONObject.fromObject(reslutData);
			LogUtil.debug("微信登录获取到登录信息={}", json);
			String openId = json.getString("openid");
			String sessionKey = json.getString("session_key");
			LogUtil.debug("openId={},sessionKey={}", openId, sessionKey);
			// 查询用户是否存在
			BizUser bizUser = bizUserDao.findByOpenId(openId);
			if (bizUser == null) {
				// 新增用户
				bizUser = new BizUser();
				bizUser.setSessionKey(sessionKey);
				bizUser.setOpenId(openId);
				bizUser.setLastLoginTime(new Date());
				bizUserService.add(bizUser);
			} else {
				bizUser.setSessionKey(sessionKey);
				bizUser.setLastLoginTime(new Date());
				// 更新用户sessionKey
				bizUserService.modifyByModel(bizUser);
			}
			// 存放redis
			String token = redisUserLoginUtils.saveUserInfo(bizUser);
			LogUtil.info("用户token={}", token);
			
			res.putInMap("token", token);
			res.putInMap("userInfo", bizUser);
			res.setStatus(AjaxResult.STATUS_SUCCESS);
			
		} else {
			res.setStatus(AjaxResult.STATUS_FAIL);
			res.setInfo("自动登录失败");
		}
		return res;
	}

	/**
	 * 查询用户信息
	 */
	@RequestMapping(value = "/findUserInfo")
	public @ResponseBody AjaxResult findUserInfo() {
		BizUser loginUser = redisUserLoginUtils.getLoginUser();
		BizUser bizUser = bizUserDao.findByOpenId(loginUser.getOpenId());
		// 存放redis
					//String token = redisUserLoginUtils.saveUserInfo(bizUser);
					//LogUtil.info("用户token={}", token);
					AjaxResult res = new AjaxResult();
					//res.putInMap("token", token);
					res.putInMap("userInfo", bizUser);
					res.setStatus(AjaxResult.STATUS_SUCCESS);
					return res;
		
	}
	/**
	 * 接收用户信息
	 */
	@RequestMapping(value = "/saveUserInfo")
	public @ResponseBody AjaxResult saveUserInfo(@RequestBody BizUser bizUser) {

		BizUser loginUser = redisUserLoginUtils.getLoginUser();
		LogUtil.info("获取到登录用户={}", loginUser);
		LogUtil.info("保存的用户={}", bizUser);
		bizUser.setUserId(loginUser.getUserId());
		// TODO 赋值操作
		int i = bizUserService.saveUserInfo(bizUser);
		if (i == 0) {
			return new AjaxResult(AjaxResult.STATUS_FAIL, "");
		}
		return new AjaxResult(AjaxResult.STATUS_SUCCESS, "");
	}

}